<template>
  <!-- <el-dialog v-model="visible" top="100px" append-to-body fullscreen title="PDF PREVIEW"  width="80%"  @close="closeDialog">
    <div class="pdf-viewer" ref="pdfContainer">
      <vue-pdf-app theme="dark"  style="height:calc(100vh - 80px);width: 100%;" :pdf="pdfUrl"></vue-pdf-app>
    </div>
  </el-dialog> -->
  <div class="pdf-viewer" ref="pdfContainer">
    <vue-pdf-app v-if="isPdfUrl || isBase64Pdf" theme="dark"  style="height:100%;width: 100%;" :pdf="pdfUrl"></vue-pdf-app>
    <div v-else-if="pdfUrl.includes('txt')" class="txt-content" style="white-space: pre-wrap;">
      {{ content }}
    </div>
    <iframe 
    v-else
      :src="`https://view.officeapps.live.com/op/view.aspx?src=${encodeURIComponent(pdfUrl)}`"
      width="100%"
      height="100%"
      frameborder="0"
    ></iframe>
    </div>
</template>

<script setup>
  import { ref } from "vue"
  import VuePdfApp from "vue3-pdf-app"
  import "vue3-pdf-app/dist/icons/main.css"
  import { useRoute } from "vue-router"
  import axios from 'axios';
  const route = useRoute()
  const pdfUrl = ref(route.query.pdfUrl)
  const props = defineProps({
    // pdfUrl: {
    //   type: String,
    //   required: true
    // },
    // modelValue: {
    //     type: Boolean,
    //     required: true
    // }
  })

// const emit = defineEmits(["update:modelValue"])
// const visible = ref(false)
const content = ref("")

watch(
  () => route.query.pdfUrl,
  async(newVal) => {
    if(newVal.includes('txt')){
      try {
        const response = await axios.get(newVal, {
          responseType: 'blob', // 设置响应类型为 blob
        });
        const blob = new Blob([response.data], { type: 'text/plain' });
        const reader = new FileReader();
        reader.onload = (e) => {
          content.value = e.target.result; // 将文件内容赋值给 textContent
        };
        reader.readAsText(blob, 'GBK'); // 指定文件编码为 GBK
      } catch (error) {
        console.error('加载文件失败:', error);
        content.value = '加载文件失败，请检查文件地址是否正确。';
      }
    }
  },
  { immediate: true }
);
// const closeDialog = () => {
//   visible.value = false;
//   emit("update:modelValue", false);
// }
// 计算属性：判断是否为Base64编码的PDF
  const isBase64Pdf = computed(() => {
    return typeof pdfUrl.value === 'string' && pdfUrl.value.startsWith('data:application/pdf;base64,')
  })
  // 计算属性：判断是否为PDF链接
  const isPdfUrl = computed(() => {
    return typeof pdfUrl.value === 'string' && pdfUrl.value.toLowerCase().includes('pdf')
  })
const pdfContainer = ref(null);
onMounted(() => {
  nextTick(() => {
    // 确保容器已渲染后再操作
    if (pdfContainer.value) {
      // 示例：滚动到顶部
      pdfContainer.value.scrollTo({ top: 0 });
    }
  });
});
</script>

<style scoped>
.pdf-viewer {
  width: 100%;
  height: 100%;
}
</style>